<template>
  <div class="patient-diagnosis-records">
    <div class="panel-header">
      <h2><el-icon><Document /></el-icon> 我的诊断记录</h2>
      <el-button type="primary" @click="refreshRecords">
        <el-icon><Refresh /></el-icon> 刷新记录
      </el-button>
    </div>

    <div class="diagnosis-filter">
      <el-date-picker
          v-model="dateRange"
          type="daterange"
          range-separator="至"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          :disabled-date="disabledFutureDates"
      />
      <el-select v-model="filterDepartment" placeholder="选择科室" clearable>
        <el-option
            v-for="dept in departmentList"
            :key="dept"
            :label="dept"
            :value="dept"
        />
      </el-select>
    </div>

    <div class="diagnosis-list">
      <el-timeline v-if="filteredRecords.length > 0">
        <el-timeline-item
            v-for="(record, index) in filteredRecords"
            :key="index"
            :timestamp="formatDate(record.visitTime)"
            placement="top"
        >
          <el-card class="diagnosis-card" shadow="hover" @click="showDetail(record)">
            <div class="card-header">
              <span class="hospital">{{ record.hospital || '未知医院' }}</span>
              <span class="department">{{ record.department || '未知科室' }}</span>
              <el-tag :type="record.visitType === '门诊' ? 'success' : 'danger'">
                {{ record.visitType || '未知类型' }}
              </el-tag>
            </div>
            <div class="diagnosis-content">
              <h4>诊断结果：</h4>
              <p>{{ record.diagnosis?.mainDiagnosis || '暂无诊断信息' }}</p>
              <div v-if="record.diagnosis?.secondaryDiagnoses?.length" class="secondary-diagnoses">
                <span>其他诊断：</span>
                <el-tag
                    v-for="(diag, i) in record.diagnosis.secondaryDiagnoses"
                    :key="i"
                    size="small"
                >
                  {{ diag }}
                </el-tag>
              </div>
            </div>
          </el-card>
        </el-timeline-item>
      </el-timeline>

      <el-empty v-else description="暂无诊断记录" />
    </div>

    <!-- 诊断详情对话框 -->
    <el-dialog
        v-model="detailDialogVisible"
        title="诊断详情"
        width="60%"
    >
      <div v-if="currentRecord" class="diagnosis-detail">
        <div class="detail-header">
          <h3>{{ currentRecord.hospital || '未知医院' }}</h3>
          <div class="meta-info">
            <span>{{ formatDateTime(currentRecord.visitTime) }}</span>
            <el-tag>{{ currentRecord.department || '未知科室' }}</el-tag>
            <el-tag :type="currentRecord.visitType === '门诊' ? 'success' : 'danger'">
              {{ currentRecord.visitType || '未知类型' }}
            </el-tag>
          </div>
        </div>

        <div class="detail-section">
          <h4>主诊医生：</h4>
          <p>{{ currentRecord.doctor || '未知医生' }}</p>
        </div>

        <div class="detail-section">
          <h4>主诊断：</h4>
          <p>{{ currentRecord.diagnosis?.mainDiagnosis || '暂无主诊断' }}</p>
        </div>

        <div v-if="currentRecord.diagnosis?.secondaryDiagnoses?.length" class="detail-section">
          <h4>其他诊断：</h4>
          <div class="diagnosis-tags">
            <el-tag
                v-for="(diag, i) in currentRecord.diagnosis.secondaryDiagnoses"
                :key="i"
            >
              {{ diag }}
            </el-tag>
          </div>
        </div>

        <div v-if="currentRecord.diagnosis?.treatmentPlan" class="detail-section">
          <h4>治疗方案：</h4>
          <p>{{ currentRecord.diagnosis.treatmentPlan }}</p>
        </div>

        <div v-if="currentRecord.diagnosis?.medications?.length" class="detail-section">
          <h4>用药信息：</h4>
          <el-table :data="currentRecord.diagnosis.medications" border>
            <el-table-column prop="name" label="药品名称" />
            <el-table-column prop="specification" label="规格" />
            <el-table-column prop="dosage" label="用量" />
            <el-table-column prop="frequency" label="频次" />
            <el-table-column prop="days" label="天数" />
          </el-table>
        </div>

        <div v-if="currentRecord.diagnosis?.notes" class="detail-section">
          <h4>医生备注：</h4>
          <p>{{ currentRecord.diagnosis.notes }}</p>
        </div>

        <div v-if="currentRecord.diagnosis?.followUpAdvice" class="detail-section">
          <h4>复诊建议：</h4>
          <p>{{ currentRecord.diagnosis.followUpAdvice }}</p>
        </div>
      </div>
      <template #footer>
        <el-button @click="detailDialogVisible = false">关闭</el-button>
        <el-button type="primary" @click="printDiagnosis">打印记录</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import { ref, computed, onMounted } from 'vue'
import { Document, Refresh } from '@element-plus/icons-vue'
import dayjs from 'dayjs'
import axios from "axios";

export default {
  name: 'PatientDiagnosisRecords',
  components: {
    Document,
    Refresh,
    Loading
  },
  setup() {
    const records = ref([])
    const dateRange = ref([])
    const filterDepartment = ref('')
    const detailDialogVisible = ref(false)
    const currentRecord = ref(null)

    // 模拟科室数据
    const departmentList = ref([
      '内科', '外科', '儿科', '妇产科', '眼科',
      '耳鼻喉科', '口腔科', '皮肤科', '中医科'
    ])

    // 模拟获取诊断记录
    // 获取后端数据
    const fetchRecords = async () => {
      try {
        const response = await axios.get('http://localhost:6063/api/diagnosis-records/all')
        if (response.data?.data) {
          records.value = response.data.data.map(item => ({
            id: item.id,
            hospital: item.hospital,
            department: item.department,
            visitType: item.visitType,
            visitTime: item.visitTime,
            doctor: item.doctor,
            diagnosis: {
              mainDiagnosis: item.mainDiagnosis,
              secondaryDiagnoses: item.secondaryDiagnoses ? JSON.parse(item.secondaryDiagnoses) : [],
              treatmentPlan: item.treatmentPlan,
              medications: item.medications ? JSON.parse(item.medications) : [],
              notes: item.notes,
              followUpAdvice: item.followUpAdvice
            }
          }))
        }
      } catch (error) {
        console.error('获取诊断记录失败:', error)
        ElMessage.error('获取诊断记录失败')
      }
    }
    // 过滤后的记录
    const filteredRecords = computed(() => {
      let result = records.value

      // 按日期过滤
      if (dateRange.value && dateRange.value.length === 2) {
        const [start, end] = dateRange.value
        result = result.filter(record => {
          const recordDate = new Date(record.visitTime)
          return recordDate >= start && recordDate <= end
        })
      }

      // 按科室过滤
      if (filterDepartment.value) {
        result = result.filter(record =>
            record.department === filterDepartment.value
        )
      }

      return result
    })

    // 刷新记录
    const refreshRecords = () => {
      fetchRecords()
    }

    // 显示详情
    const showDetail = (record) => {
      currentRecord.value = record
      detailDialogVisible.value = true
    }

    // 打印诊断
    const printDiagnosis = () => {
      window.print()
    }

    // 格式化日期
    const formatDate = (date) => {
      return dayjs(date).format('YYYY-MM-DD')
    }

    // 格式化日期时间
    const formatDateTime = (date) => {
      return dayjs(date).format('YYYY-MM-DD HH:mm')
    }

    // 禁用未来日期
    const disabledFutureDates = (time) => {
      return time.getTime() > Date.now()
    }

    onMounted(() => {
      fetchRecords()
    })

    return {
      records,
      dateRange,
      filterDepartment,
      departmentList,
      filteredRecords,
      detailDialogVisible,
      currentRecord,
      refreshRecords,
      showDetail,
      printDiagnosis,
      formatDate,
      formatDateTime,
      disabledFutureDates
    }
  }
}
</script>

<style scoped>
.patient-diagnosis-records {
  padding: 20px;
  background-color: #f5f7fa;
  min-height: 100%;
}

.panel-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.panel-header h2 {
  margin: 0;
  display: flex;
  align-items: center;
  font-size: 18px;
}

.panel-header .el-icon {
  margin-right: 8px;
}

.diagnosis-filter {
  display: flex;
  gap: 15px;
  margin-bottom: 20px;
}

.diagnosis-list {
  background-color: #fff;
  padding: 20px;
  border-radius: 4px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.diagnosis-card {
  cursor: pointer;
  transition: transform 0.3s;
  margin-bottom: 10px;
}

.diagnosis-card:hover {
  transform: translateY(-3px);
}

.card-header {
  display: flex;
  align-items: center;
  gap: 10px;
  margin-bottom: 10px;
}

.hospital {
  font-weight: bold;
  font-size: 16px;
}

.department {
  color: #666;
}

.diagnosis-content h4 {
  margin: 5px 0;
  font-size: 14px;
  color: #333;
}

.diagnosis-content p {
  margin: 5px 0 10px;
  color: #666;
}

.secondary-diagnoses {
  display: flex;
  align-items: center;
  flex-wrap: wrap;
  gap: 5px;
}

.secondary-diagnoses span {
  margin-right: 5px;
  color: #666;
}

.diagnosis-detail {
  padding: 10px;
}

.detail-header {
  margin-bottom: 20px;
  padding-bottom: 10px;
  border-bottom: 1px solid #eee;
}

.detail-header h3 {
  margin: 0 0 10px 0;
}

.meta-info {
  display: flex;
  align-items: center;
  gap: 10px;
  color: #666;
}

.detail-section {
  margin-bottom: 15px;
}

.detail-section h4 {
  margin: 0 0 8px 0;
  font-size: 15px;
  color: #333;
}

.detail-section p {
  margin: 0 0 10px 0;
  color: #666;
  line-height: 1.6;
}

.diagnosis-tags {
  display: flex;
  flex-wrap: wrap;
  gap: 8px;
}

.el-tag {
  margin-right: 5px;
}

@media print {
  .patient-diagnosis-records > *:not(.diagnosis-detail) {
    display: none;
  }

  .diagnosis-detail {
    padding: 0;
  }

  .el-dialog {
    position: static;
    margin: 0;
    box-shadow: none;
  }

  .el-dialog__header, .el-dialog__footer {
    display: none;
  }
}

@media (max-width: 768px) {
  .diagnosis-filter {
    flex-direction: column;
  }

  .card-header {
    flex-wrap: wrap;
  }
}
</style>
